package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.IFollowService;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IVoucherService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService iSeckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    private IVoucherOrderService proxy;
    //线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("/redis-lua/seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    @PostConstruct
    private void init(){
        //类初始化后执行任务
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    //下单任务
    /*************************************** 秒杀下单阻塞队列，作为异步创建订单信息的队列，在stream替代后，可抛弃 ****************************************************/
//    private BlockingQueue<VoucherOrder> orderTask = new ArrayBlockingQueue<>(1024*1024);
    private class VoucherOrderHandler implements Runnable{

        String queueName = "stream.orders";

        @Override
        public void run() {
            while (true){
                try {

                    //抛弃java阻塞队列模式，使用redis stream代替
                    //1,获取队列中的订单信息，take 是阻塞方法，当take不到，则会一直等待
//                    VoucherOrder voucherOrder = orderTask.take();

                    //获取消息队列中的订单信息 XREADGROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    if (list == null || list.isEmpty()){
                        //如果获取失败,说明没有消息
                        continue;
                    }
                    //如果获取成功，则创建订单
                    MapRecord<String, Object, Object> record = list.get(0);
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(record.getValue(), new VoucherOrder(), true);
                    //2,创建订单信息
                    handleVoucherOrder(voucherOrder);
                    //ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常",e);
                    hanlePendingList();
                }
            }
        }
        private void hanlePendingList() {
            while (true){
                try {
                    //获取消息队列中的订单信息 XREADGROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    if (list == null || list.isEmpty()){
                        //如果获取失败,说明pengding - list没有消息
                        break;
                    }
                    //如果获取成功，则创建订单
                    MapRecord<String, Object, Object> record = list.get(0);
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(record.getValue(), new VoucherOrder(), true);
                    //2,创建订单信息
                    handleVoucherOrder(voucherOrder);
                    //ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                } catch (Exception e) {
                    log.error("处理pengding-list订单异常",e);
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException ex) {
                    }
                }
            }
    }
        private void handleVoucherOrder(VoucherOrder voucherOrder) {
        //获取用户
            Long userId = voucherOrder.getUserId();
            //创建锁对象
            RLock lock = redissonClient.getLock("lock:order:" + userId);
            //获取锁
            boolean isLock = lock.tryLock();
            //判断获取结果
            if (!isLock){
                //获取锁失败
                log.error("不允许重复下单");
                return ;
            }
            try {
                proxy.createVoucherOrder(voucherOrder);
            }finally {
                lock.unlock();
            }
        }
    }

    /**
     * TODO 最终版
     * redis Stream 取代java阻塞队列，并利用lua脚本push消息。
     * */
    @Override
    public Result seckillVoucher(Long voucherId) {
        //获取userID
        Long userId = UserHolder.getUser().getId();
        // 生成订单id
        long orderId = redisIdWorker.nextId("order");
        //1,执行lua 脚本
        int execute = stringRedisTemplate.execute(
                this.SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                String.valueOf(orderId)
        ).intValue();
        // 判断结果 是否为0
        if (execute != 0) {
            // 不是0，没有购买资格
            return Result.fail(execute == 1 ? "库存不足" : "不能重复下单");
        }
        //获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        return Result.ok(orderId);
    }

    /*@Override
    public Result seckillVoucher(Long voucherId) {
        *//**
         * 1，采用LUA 脚本解决redis中，判断库存和一人一单和库存扣减等操作的原子问题。
         *//*

       *//* //获取userID
        Long userId = UserHolder.getUser().getId();
        //1,执行lua 脚本
        int execute = stringRedisTemplate.execute(
                this.SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString()
        ).intValue();
        // 判断结果 是否为0
        if (execute != 0){
            // 不是0，没有购买资格
            return Result.fail(execute == 1? "库存不足":"不能重复下单");
        }
        // 是0，有购买资格，将下单信息放入阻塞队列
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(redisIdWorker.nextId("order"));
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        orderTask.add(voucherOrder);
        //获取代理对象
        proxy = (IVoucherOrderService)AopContext.currentProxy();
        // 返回订单id
        long orderId = redisIdWorker.nextId("order");
        return Result.ok(orderId);*//*


        *//*********************************************
         * TODO 在多节点分布式场景下，采用分布式锁，实现一人一单的功能
         * 改造前，用java代码，DB 和redis 分布式锁，进行串行下单扣库存操作
         * *****************************************************************
         * *//*

       *//* SeckillVoucher seckillVoucher = iSeckillVoucherService.getById(voucherId);

        if (seckillVoucher.getBeginTime().isfter(LocalDateTime.now())) {
            return Result.fail("秒杀尚未开始");
        }
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("秒杀活动已经束");
        }
        if (seckillVoucher.getStock() < 1){
            return Result.fail("库存不足");
        }
        Long userId = UserHolder.getUser().getId();

        RLock lock = redissonClient.getLock("lock:order:" + userId);
        boolean isLock = lock.tryLock();
        if (!isLock){
            //获取锁失败
            return Result.fail("不允许重复下单");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService)AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        }finally {
            lock.unlock();
        }
        *//*

        *//**
         * 单机部署下，实现一人一单功能，采用悲观锁时间
         * 加悲观锁，注意锁粒度，只有相同用户是互斥的，所以相同userId加锁
         * //TODO 在分布式场景下，多个JVM的锁监视器不共享，所以锁会失效，控制不了一人一单。需要才用分布式锁
         * *//*
       *//* synchronized (userId.toString().intern()) {
            *//**//**
             * 获取到当前对象的代理对象，因为spring的事务的实现是依赖代理对象实现的，this对象没有事务的实现。
             * *//**//*
            IVoucherOrderService proxy = (IVoucherOrderService)AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        }

        SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order" + userId, stringRedisTemplate);
        boolean isLock = simpleRedisLock.tryLock(12000);*//*
    }*/

    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        // 实现一人一单
        Long userId = UserHolder.getUser().getId();

        Integer count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        if (count > 0) {
            return Result.fail("该用户已经购买过了");
        }
        //扣减库存
        boolean success = iSeckillVoucherService.update().setSql("stock = stock - 1").eq("voucher_id", voucherId).ge("stock", 1).update();
        //扣减失败
        if (!success) {
            return Result.fail("库存不足");
        }
        //创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(redisIdWorker.nextId("order"));
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);
        return Result.ok(voucherOrder.getId());
    }

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        // 实现一人一单
        Long userId = voucherOrder.getUserId();
        // 查询订单
        Integer count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
        if (count > 0) {
            log.error("该用户已经购买过了");
            return;
        }

        //扣减库存
        boolean success = iSeckillVoucherService.update().setSql("stock = stock - 1").eq("voucher_id", voucherOrder.getVoucherId()).ge("stock", 1).update();
        //扣减失败
        if (!success) {
            log.error("库存不足");
            return;
        }
        //创建订单
        voucherOrder.setVoucherId(voucherOrder.getVoucherId());
        save(voucherOrder);
    }

}
